#!/usr/bin/env python3
"""
Qt6 TCP Server测试客户端
用于测试服务器的连接、消息发送和接收功能
"""

import socket
import threading
import time
import sys

class TestClient:
    def __init__(self, host='127.0.0.1', port=12345):
        self.host = host
        self.port = port
        self.socket = None
        self.running = False
        
    def connect(self):
        """连接到服务器"""
        try:
            self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.socket.connect((self.host, self.port))
            print(f"已连接到服务器 {self.host}:{self.port}")
            return True
        except Exception as e:
            print(f"连接失败: {e}")
            return False
    
    def send_message(self, message):
        """发送消息到服务器"""
        if self.socket:
            try:
                self.socket.send(message.encode('utf-8'))
                print(f"发送: {message}")
            except Exception as e:
                print(f"发送失败: {e}")
    
    def receive_messages(self):
        """接收服务器消息"""
        while self.running and self.socket:
            try:
                data = self.socket.recv(1024)
                if not data:
                    break
                message = data.decode('utf-8')
                print(f"收到: {message}")
            except Exception as e:
                print(f"接收错误: {e}")
                break
    
    def start(self):
        """启动客户端"""
        if not self.connect():
            return False
            
        self.running = True
        
        # 启动接收线程
        receive_thread = threading.Thread(target=self.receive_messages)
        receive_thread.daemon = True
        receive_thread.start()
        
        print("客户端已启动，输入消息发送（输入'quit'退出）：")
        
        try:
            while self.running:
                message = input("> ")
                if message.lower() == 'quit':
                    break
                if message.strip():
                    self.send_message(message)
        except KeyboardInterrupt:
            print("\n客户端中断")
        finally:
            self.stop()
    
    def stop(self):
        """停止客户端"""
        self.running = False
        if self.socket:
            self.socket.close()
            print("客户端已断开连接")

def test_multiple_clients(num_clients=3):
    """测试多个客户端同时连接"""
    def client_task(client_id):
        client = TestClient()
        if client.connect():
            client.send_message(f"Hello from client {client_id}")
            time.sleep(2)
            client.send_message(f"Client {client_id} is still here")
            time.sleep(1)
            client.stop()
    
    threads = []
    for i in range(num_clients):
        thread = threading.Thread(target=client_task, args=(i,))
        threads.append(thread)
        thread.start()
    
    for thread in threads:
        thread.join()

if __name__ == "__main__":
    if len(sys.argv) > 1 and sys.argv[1] == "multi":
        print("测试多个客户端...")
        test_multiple_clients()
    else:
        client = TestClient()
        client.start()